﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FONCREAGROINTEGRAL.Models;

namespace FONCREAGROINTEGRAL.Controllers
{
    public class posicionController : Controller
    {
        public SistIntFoncreagroEntities entidades = new SistIntFoncreagroEntities();
                //
        // GET: /posicion/
        public ActionResult IndexJefeInmediato(int id)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            string cargo = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.POSICIONs
                .Where(p => p.IdArea == id)
                .Join(entidades.CARGOes, p => p.IdCargo, c => c.IdCargo, (p, c) => new { p.IdPosicion, c.NomCargo, p.JefeInmediato });
            if (!String.IsNullOrEmpty(cargo))
            {
                query = query.Where(p => (p.NomCargo).ToUpper().Contains(cargo.ToUpper()));
            }
            var result = (from p in query.OrderBy(p => p.NomCargo).Skip(start).Take(limit).ToList()
                          join rp in entidades.POSICIONs on p.JefeInmediato equals rp.IdPosicion into vrp
                          from x in vrp.DefaultIfEmpty()
                          select new
                          {
                              IdPosicionJefeInmediato = p.IdPosicion,
                              NomCargoJefeInmediato = p.NomCargo,
                              IdJefe = (x == null ? 0 : x.IdPosicion),
                              CargoJefe = (x == null ? String.Empty : CargoJefe(x.IdPosicion)),
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult IndexConId(int id)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            string cargo = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.POSICIONs
                .Where(p => p.IdArea == id)
                .Join(entidades.CARGOes, p => p.IdCargo, c => c.IdCargo, (p, c) => new {p.IdPosicion,c.NomCargo,p.JefeInmediato});
            if (!String.IsNullOrEmpty(cargo))
            {
                query = query.Where(p => (p.NomCargo).ToUpper().Contains(cargo.ToUpper()));
            }
            var result = (from p in query.OrderBy(p => p.NomCargo).Skip(start).Take(limit).ToList()
                          join rp in entidades.POSICIONs on p.JefeInmediato equals rp.IdPosicion into vrp
                          from x in vrp.DefaultIfEmpty()
                          select new
                          {
                              IdPosicion = p.IdPosicion,
                              NomCargo = p.NomCargo,
                              IdJefe = (x == null ? 0 : x.IdPosicion),
                              CargoJefe = (x == null ? String.Empty : CargoJefe(x.IdPosicion)),
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }
        public string CargoJefe(int id)
        {
            //var mes = "";
            var query = entidades.POSICIONs
               .Where(p => p.IdPosicion == id)
               .Join(entidades.CARGOes, p => p.IdCargo, c => c.IdCargo, (p, c) => new { p.IdPosicion, c.NomCargo, p.JefeInmediato });

            return query.Single(c => c.IdPosicion == id).NomCargo;
        }
        //
        // GET: /posicion/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /posicion/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /posicion/Create

        //public ActionResult Create()
        //{
        //    List<SelectListItem> siono = new List<SelectListItem>();
        //    siono.Add(new SelectListItem { Text = "NO", Value = "false" });
        //    siono.Add(new SelectListItem { Text = "SI", Value = "true" });

        //    ViewData["Confianza"] = new SelectList(siono.AsEnumerable(), "value", "text",false);
        //    ViewData["JefeArea"] = new SelectList(siono.AsEnumerable(), "value", "text",false);

        //    return View();
        //} 

        //
        // POST: /posicion/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection, POSICION POSICION)
        {
            //List<SelectListItem> siono = new List<SelectListItem>();
            //siono.Add(new SelectListItem { Text = "NO", Value = "false" });
            //siono.Add(new SelectListItem { Text = "SI", Value = "true" });
            int JefeInmediato = Convert.ToInt32(Request.QueryString["JefeInmediato"]);
            //ViewData["Confianza"] = new SelectList(siono.AsEnumerable(), "value", "text");
            //ViewData["JefeArea"] = new SelectList(siono.AsEnumerable(), "value", "text");
            string strResponse = String.Empty;

            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    var cposicion = new POSICION();
                    TryUpdateModel(cposicion, collection.ToValueProvider());
                    if (JefeInmediato == 0)
                    {
                        cposicion.JefeInmediato = null;
                    }
                    cposicion.FechaCreacion = DateTime.Now;
                    entidades.AddToPOSICIONs(cposicion);
                    entidades.SaveChanges();
                    strResponse = "{success: true,msg:'Registro Creado Correctamente'}";
                    return Content(strResponse);
                }
                strResponse = "{success: false,msg:'Su Registro No Se Pudo Crear'}";
                return Content(strResponse);
            }
            catch (Exception e)
            {
                strResponse = "{success: true,msg:'" + e.Message + "'}";
                return Content(strResponse);
            }
        }
        
        //
        // GET: /posicion/Edit/5
        public ActionResult GetPosicionById(int id)
        {
            var eposicion = entidades.POSICIONs.Single(pos => pos.IdPosicion == id);
            List<SelectListItem> siono = new List<SelectListItem>();
            siono.Add(new SelectListItem { Text = "NO", Value = "false" });
            siono.Add(new SelectListItem { Text = "SI", Value = "true" });

            var query = entidades.POSICIONs.Where(pos => pos.IdPosicion == id);

            var result = (from p in query.ToList()
                          join c in entidades.CARGOes on p.IdCargo equals c.IdCargo
                          join ji in entidades.POSICIONs on p.JefeInmediato equals ji.IdPosicion into lji
                          from y in lji.DefaultIfEmpty()

                          join cji in entidades.CARGOes on (y == null ? 0 : y.IdCargo) equals cji.IdCargo into lcji
                          from x in lcji.DefaultIfEmpty()

                          select new
                          {
                              NomCargoJefeInmediato = (x == null ? String.Empty : x.NomCargo),
                              IdPosicionJefeInmediato = (y == null ? 0 : y.IdPosicion),
                              c.NomCargo,
                              p.IdCargo,
                              p.JefeArea,
                              p.Confianza
                          });

            return Json(new { Grid = result,Total = result.Count()},JsonRequestBehavior.AllowGet);
        }

        //public ActionResult Edit(int id)
        //{
        //    var eposicion = entidades.POSICIONs.Single(pos => pos.IdPosicion == id);
        //    List<SelectListItem> siono = new List<SelectListItem>();
        //    siono.Add(new SelectListItem { Text = "NO", Value = "false" });
        //    siono.Add(new SelectListItem { Text = "SI", Value = "true" });

        //    ViewData["Confianza"] = new SelectList(siono.AsEnumerable(), "value", "text", eposicion.Confianza);
        //    ViewData["JefeArea"] = new SelectList(siono.AsEnumerable(), "value", "text", eposicion.JefeArea);

        //    return View(eposicion);
        //}

        //
        // POST: /posicion/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            string strResponse = String.Empty;
            var eposicion = entidades.POSICIONs.Single(pos => pos.IdPosicion == id);

            int JefeInmediato = Convert.ToInt32(Request.QueryString["JefeInmediato"]);

            
            //List<SelectListItem> siono = new List<SelectListItem>();
            //siono.Add(new SelectListItem { Text = "NO", Value = "false" });
            //siono.Add(new SelectListItem { Text = "SI", Value = "true" });

            //ViewData["Confianza"] = new SelectList(siono.AsEnumerable(), "value", "text", eposicion.Confianza);
            //ViewData["JefeArea"] = new SelectList(siono.AsEnumerable(), "value", "text", eposicion.JefeArea);
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    TryUpdateModel(eposicion);
                    if (JefeInmediato == 0)
                    {
                        eposicion.JefeInmediato = null;
                    }
                    entidades.SaveChanges();
                    strResponse = "{success: true,msg:'Registro Creado Correctamente'}";
                    return Content(strResponse);
                }
                strResponse = "{success: false,msg:'El Registro No Se Actualizo'}";
                return Content(strResponse);
            }
            catch(Exception e)
            {
                strResponse = "{success: true,msg:'"+e.Message+"'}";
                return Content(strResponse);
            }
        }

        //
        // GET: /posicion/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /posicion/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
